const socket = io("http://localhost:3000/");

console.log("server started");

let newGamebutton = document.getElementById("new-game-button");
let joinGamebutton = document.getElementById("join-game-button");
let chooseGameDiv = document.getElementById("choose-game");
let lobbyDiv = document.getElementById("lobby-content");
let roomCode = document.getElementById("room-code");
let message = document.getElementById("msg");
let roomCodeHeader = document.getElementById("room-code-header");
let startGameButton = document.getElementById("start-game-button");
let gamePage = document.getElementById("game-page");
let playerList = document.getElementById("players");
let name = document.getElementById("name");
let votingDiv = document.getElementById("voting-page");
let categoryButton = document.getElementById("category-game-button");
let playDiv = document.getElementById("play-page");
let revealItemButton = document.getElementById("reveal-item-button");
let revealItemDiv = document.getElementById("reveal-item-page");
let readyButton = document.getElementById("ready-button");
let questionsDiv = document.getElementById("questions-page");
let nextQuestionButton = document.getElementById("next-question-button");
let playAgainButton = document.getElementById("play-again-button");
let playerListAgain = document.getElementById("playerlist");
let playerPlay = document.getElementById("player-play");
let playerNamesButton = document.getElementById("player-names-button");
let playerButtons = document.getElementById("player-buttons");
let playerReveal = document.getElementById("player-reveal");
let food = document.getElementById("food");
let yourItemIs = document.getElementById("your-item-is");
let ask = document.getElementById("player-ask");
let asked = document.getElementById("player-asked");
let question = document.getElementById("question");
let scoresDiv = document.getElementById("scores-page");
let imposterReveal = document.getElementById("imposter-reveal");
let imposterRevealName = document.getElementById("imposter-reveal-name");
let howToPlayButton = document.getElementById("how-to-play-button");
let howToPlayDiv = document.getElementById("how-to-instructions");
let sendChatMessage = document.getElementById("send-chat-message");
let chatMessages = document.getElementById("chat-messages");
let inputChatMessage = document.getElementById("chat-message");
let hamburgerButton = document.getElementById("hamburger-button");
let hamburgerMenu = document.getElementById("menu");

const foods = ["Pizza \u{1F355}", "Cottage Pie", "A Mango \u{1F96D}", "Caviar \u{1F95A}", "Pancakes \u{1F95E}", "Veggie Burger \u{1F354}"];
const players = ["",""];
const questions = ["Could you identify any special nutritional components in this food?",
"What are the bodily benefits of consuming this food?",
"In which occasions is this food typically utilized?",
"Does this food hold any special significance in a particular culture or country?",
"What flavor profile does this food predominantly exhibit?",
"Have you had the opportunity to taste this food?",
"Where have you tasted this food?",
"Who is most likely to appreciate it in its natural setting?",
"Would you find it astonishing if someone devoted eight hours to making this?",
"If an elf granted you the power to create twelve of these daily but forbidden you from consuming them, would you accept?",
"Is there any practical utility of this food beyond eating?",
"Can it serve as an ingredient in other preparations?",
"Is it probable that this food would appear on a five-star hotel's menu?",
"Would you pair it with ice cream?",
"Have you ever attempted to make this food yourself?",
"Where is this food most popular globally?",
"If you could purchase it inexpensively, how frequently would you consume it?",
"How likely are you to eat it if it accidentally drops on a relatively clean floor?",
"How much do you think people are willing to pay for this food?",
];
const pairArray = [];


let hideContent = "none";
let showContent = "block";

let globalPlayerName = "";
let globalRoomCode = 0;

newGamebutton.addEventListener("click", () => { 
    console.log("new game button clicked");
    let playerName = name.value;
    let roomCode = Math.floor(Math.random() * 1000000);
    globalRoomCode = roomCode;
    if(playerName === "") {
        alert("Please enter a name");
    } else {
        handleGameButtonClick(hideContent, showContent, hideContent, hideContent, hideContent, hideContent, hideContent, hideContent); 
        globalPlayerName = playerName;
        console.log("Player pressed new game " + {name: playerName, roomCode: roomCode});
        socket.emit("new-game", {name: playerName, roomCode: roomCode});
    }
});

joinGamebutton.addEventListener("click", () => { 
    console.log("join game button clicked");
    let playerName = name.value;
    let roomCodeValue = roomCode.value;
    if(roomCodeValue.length > 0 && !isNaN(roomCodeValue)){
        if(playerName === "") {
            alert("Please enter a name");
        } else {
            handleGameButtonClick(hideContent, showContent, hideContent, hideContent, hideContent, hideContent, hideContent, hideContent);
            globalPlayerName = playerName;
            console.log("Player pressed join game " + {code : roomCodeValue, name : playerName});
            roomCodeValue = parseInt(roomCodeValue);
            globalRoomCode = roomCodeValue;
            socket.emit("join-game", {code : roomCodeValue, name : playerName});
        }
    } else {
        alert("Please enter a valid room code");
    }
});

hamburgerButton.addEventListener("click", () => {
    if(hamburgerMenu.style.display === showContent) {
        hamburgerMenu.style.display = hideContent;
    } else {
        hamburgerMenu.style.display = showContent;
    }
});


howToPlayButton.addEventListener("click", () => {
    
    if(howToPlayDiv.style.display === showContent) {
        howToPlayDiv.style.display = hideContent;
    } else {
        howToPlayDiv.style.display = showContent;
    }
    
});

startGameButton.addEventListener("click", () => {
    console.log("start game button clicked");
    let roomCodeValue = roomCode.value;
    let playerName = name.value;
    console.log(roomCodeValue);
    socket.emit("start-game", {code : globalRoomCode, name : playerName});
});

categoryButton.addEventListener("click", () => { 
    console.log("category button clicked");
    let roomCodeValue = roomCode.value;
    let playerName = name.value;
    socket.emit("reveal-waiting", {code : globalRoomCode, name : playerName});
});

revealItemButton.addEventListener("click", () => {
    console.log("reveal item button clicked");
    let roomCodeValue = roomCode.value;
    let playerName = name.value;
    socket.emit("reveal-item", {code : globalRoomCode, name : playerName});
});

readyButton.addEventListener("click", () => {
    console.log("ready button clicked");
    let roomCodeValue = roomCode.value;
    let playerName = name.value;
    socket.emit("players-ready", {code : globalRoomCode, name : playerName});
});

nextQuestionButton.addEventListener("click", () => {
    console.log("next question button clicked");
    let roomCodeValue = roomCode.value;
    let playerName = name.value;
    socket.emit("voting-start", {code : globalRoomCode, name : playerName});
});

playAgainButton.addEventListener("click", () => {
    console.log("play again button clicked"); 
    handleGameButtonClick(showContent, hideContent, hideContent, hideContent, hideContent, hideContent, hideContent, hideContent); 
});

sendChatMessage.onclick = () => {
    let playerName = name.value;
    globalPlayerName = playerName;
    let val = document.getElementById("chat-message").value;
    console.log("Text: " + val);
    inputChatMessage.value = "";
    inputChatMessage.focus();
    console.log({ message : val, name : playerName, roomCode : globalRoomCode});
    socket.emit('chat-message-send', { message : val, name : playerName, roomCode : globalRoomCode});
    updateContent.style.display = showContent;
};

socket.on('message', data => {
    console.log(data.message);
    let p = document.createElement("p");
    p.innerHTML = data.name + ": " + data.message;
    chatMessages.appendChild(p);
});

socket.on('room-code', data => {
    console.log("room code: " + data);
    roomCodeHeader.innerHTML = data;
});

socket.on('player-names', data => {
    console.log("lobby names: " + data);
    playerList.innerHTML = "";
    for(let i = 1; i <= data.length; i++) {
        console.log(data[i-1].name);
        let p = document.createElement("p");
        p.innerHTML = `${i}. ${data[i-1].name}`;
        playerList.appendChild(p); 
    }
});

socket.on('player-names-again', data => {
    console.log("lobby names: " + data);
    playerListAgain.innerHTML = "";
    for(let i = 1; i <= data.length; i++) {
        console.log(data[i-1].name);
        let p = document.createElement("p");
        p.innerHTML = `${i}. ${data[i-1].name}`;
        playerListAgain.appendChild(p); 
    }
});

socket.on('categories-stage', data => {
    handleGameButtonClick(hideContent, hideContent, showContent, hideContent, hideContent, hideContent, hideContent, hideContent);
});

socket.on('player-roles-stage', data => { 
    handleGameButtonClick(hideContent, hideContent, hideContent, showContent, hideContent, hideContent, hideContent, hideContent);

    let playerName = name.value;
     playerPlay.innerHTML = playerName;
});

socket.on('roles-reveal-stage', data => {
    handleGameButtonClick(hideContent, hideContent, hideContent, hideContent, showContent, hideContent, hideContent, hideContent);
    let playerName = name.value;
    
    playerReveal.innerHTML = playerName;

   let selectedFood = data.food;
   let players = data.players;
   
   
   players.forEach(player => {
       if(player.name === globalPlayerName){
           if(player.imposter == true){
                
                selectedFood = "Imposter!";
            } else {
                yourItemIs.innerHTML = "Your item is: ";
            }
        }
    })
    
    food.innerHTML = selectedFood;
});

socket.on('questions-stage', data => { 
    handleGameButtonClick(hideContent, hideContent, hideContent, hideContent, hideContent, showContent, hideContent, hideContent);

    let playerasked = "";

    data.forEach(function(player, index, theArray) {
        console.log(player.name);
        if(player.name == globalPlayerName){
            
            if(index == theArray.length - 1){
                playerasked = theArray[0].name;
            }
            else{
                playerasked = theArray[index+1].name;
            }
        }
    });
    
    ask.innerHTML = globalPlayerName + " ask:";
    asked.innerHTML = playerasked;
    question.innerHTML = randomQuestion();

    function randomQuestion() {
        return questions[Math.floor(Math.random() * questions.length)];
    }
});

socket.on('voting-start-stage', ({ players, code }) => {
    handleGameButtonClick(hideContent, hideContent, hideContent, hideContent, hideContent, hideContent, showContent, hideContent);
    
    playerButtons.innerHTML = "";
    
    for(let i = 1; i <= players.length; i++) {
        console.log(players[i-1].name);
        let button = document.createElement("button");
        button.innerHTML = `${i}. ${players[i-1].name}`;
        button.setAttribute("id", `${players[i-1].name}`);
        button.setAttribute("class", "button-class");
        playerButtons.appendChild(button); 
        button.onclick = () => {
            socket.emit("vote", {name : players[i-1].name, code : code});
            console.log(players[i-1].name + " vote button pressed");
        }
    }

    function NoOfVotes() {
        var numberOfVotes = 0;
        for (var i = 0; i < data.length; i++) {
            numberOfVotes = numberOfVotes + data[i].votes;
        }
        return numberOfVotes;
    }
    
    function VoteFor(string) {
        if (NoOfVotes() < data.length) {
            for (var i = 0; i < data.length; i++) {
                if (string == data[i].name) {
                    data[i].votes = data[i].votes + 1;
                }
            }
        }
    }
});

socket.on('score-stage', ({ won, imposter }) => {
    handleGameButtonClick(hideContent, hideContent, hideContent, hideContent, hideContent, hideContent, hideContent, showContent);
    if(won){
        imposterReveal.innerHTML = "The team guessed correct! <br>";
        imposterRevealName.innerHTML = imposter.name;
    } else {
        imposterReveal.innerHTML = "The team guessed incorrect! <br> ";
        imposterRevealName.innerHTML = imposter.name;
    }
});


function handleGameButtonClick(chooseGameStyle, lobbyStyle, gameStyle, playStyle, revealItemStyle, questionsStyle, votingStyle, scoresStyle) {
    console.log("game button clicked");
    chooseGameDiv.style.display = chooseGameStyle;
    lobbyDiv.style.display = lobbyStyle;
    gamePage.style.display = gameStyle;
    playDiv.style.display = playStyle;
    revealItemDiv.style.display = revealItemStyle;
    questionsDiv.style.display = questionsStyle;
    votingDiv.style.display = votingStyle;
    scoresDiv.style.display = scoresStyle;
}


inputChatMessage.addEventListener("keypress", function(event) {
    if (event.keyCode === 13) {
        event.preventDefault();
        sendChatMessage.click();
    }
});